package com.gzx.plugin.tjzy.modular.excel.imports.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzx.plugin.tjzy.modular.allocate.entity.vo.GzxAllocateCaseExcelVo;
import com.gzx.plugin.tjzy.modular.excel.imports.bo.GzxExcelImportQueryBo;
import com.gzx.plugin.tjzy.modular.excel.imports.consts.GzxFileHandleStatusConstant;
import com.gzx.plugin.tjzy.modular.excel.imports.consts.GzxFileTypeConstant;
import com.gzx.plugin.tjzy.modular.excel.imports.entity.GzxExcelImport;
import com.gzx.plugin.tjzy.modular.excel.imports.mapper.GzxExcelImportMapper;
import com.gzx.plugin.tjzy.modular.excel.imports.service.GzxExcelImportService;
import com.gzx.plugin.tjzy.modular.excel.imports.vo.GzxExcelImportVo;
import com.gzx.plugin.tjzy.modular.file.consts.GzxFileBucketConstant;
import com.gzx.plugin.tjzy.modular.file.service.FileService;
import com.gzx.plugin.tjzy.modular.gzxcase.vo.GzxCaseExcelVo;
import com.gzx.plugin.tjzy.modular.liaison.entity.vo.GzxDebtorLiaisonImportVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.util.CommonExcelUtil;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;

/**
 * @author zjt
 * @description
 * @date 2025/5/8 14:03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GzxExcelImportServiceImpl implements GzxExcelImportService {

    private final FileService fileService;

    private final GzxExcelImportMapper excelImportMapper;

    /**
     * 分页查询
     *
     * @param excelImportQueryBo
     * @return
     */
    @Override
    @DS("tjzy")
    public Page<GzxExcelImportVo> pageList(GzxExcelImportQueryBo excelImportQueryBo) {
        return excelImportMapper.selectVoPage(new Page<>(excelImportQueryBo.getCurrent(), excelImportQueryBo.getSize()), Wrappers.<GzxExcelImport>lambdaQuery()
                .orderByDesc(GzxExcelImport::getId));
    }

    @Override
    @DS("tjzy")
    public void importExcel(Integer type, MultipartFile multipartFile) throws IOException {
        int rowCount = CommonExcelUtil.getExcelRowCount(multipartFile, true);
        if (rowCount == 0) {
            throw new CommonException("Excel不能为空");
        }
        String fileName = fileService.upload(GzxFileBucketConstant.EXCEL_ASYNC, multipartFile, true);
        if (StringUtils.isBlank(fileName)) {
            throw new CommonException("文件上传失败");
        }
        GzxExcelImport excelImport = new GzxExcelImport();
        excelImport.setType(type);
        excelImport.setStatus(GzxFileHandleStatusConstant.PENDING);
        excelImport.setTotalCount(rowCount);
        excelImport.setFileUrl(fileName);
        excelImportMapper.insert(excelImport);
    }

    /**
     * 开始处理Excel
     *
     * @param id
     */
    @Override
    @DS("tjzy")
    public void startProcess(Long id) {
        GzxExcelImport excelImport = new GzxExcelImport();
        excelImport.setId(id);
        excelImport.setStatus(GzxFileHandleStatusConstant.IN_PROGRESS);
        excelImportMapper.updateById(excelImport);
    }

    /**
     * Excel处理流程
     */
    @Override
    @DS("tjzy")
    public void excelProcess() {
        //从数据库查询进行中的文件
        GzxExcelImport excelImport = excelImportMapper.selectOne(Wrappers.<GzxExcelImport>lambdaQuery()
                .eq(GzxExcelImport::getStatus, GzxFileHandleStatusConstant.IN_PROGRESS)
                .last("limit 1"));
        if (excelImport != null) {
            File file = null;
            int rowSize = 10;
            int listSize = 0;
            try {
                file = fileService.download(GzxFileBucketConstant.EXCEL_ASYNC, excelImport.getFileUrl());
                //案件
                if (Objects.equals(excelImport.getType(), GzxFileTypeConstant.CASE)) {
                    List<GzxCaseExcelVo> caseExcelVoList = CommonExcelUtil.importExcel(file, GzxCaseExcelVo.class,
                            excelImport.getCompletedCount() + excelImport.getErrorCount(), rowSize);
                    listSize += caseExcelVoList.size();
                }
                //联系人
                else if (Objects.equals(excelImport.getType(), GzxFileTypeConstant.LIAISON)) {
                    List<GzxDebtorLiaisonImportVo> debtorLiaisonImportVoList = CommonExcelUtil.importExcel(file,
                            GzxDebtorLiaisonImportVo.class, excelImport.getCompletedCount() + excelImport.getErrorCount(), rowSize);
                    listSize += debtorLiaisonImportVoList.size();
                }
                //分案
                else if (Objects.equals(excelImport.getType(), GzxFileTypeConstant.ALLOCATE)) {
                    List<GzxAllocateCaseExcelVo> allocateCaseExcelVoList = CommonExcelUtil.importExcel(file,
                            GzxAllocateCaseExcelVo.class, excelImport.getCompletedCount() + excelImport.getErrorCount(), rowSize);
                    listSize += allocateCaseExcelVoList.size();
                }
                //示例
                else if (Objects.equals(excelImport.getType(), GzxFileTypeConstant.DEMO)) {
                    List<GzxCaseExcelVo> caseExcelVoList = CommonExcelUtil.importExcel(file, GzxCaseExcelVo.class,
                            excelImport.getCompletedCount() + excelImport.getErrorCount(), rowSize);
                    listSize += caseExcelVoList.size();
                    System.out.println(caseExcelVoList);
                }
                excelImport.setCompletedCount(excelImport.getCompletedCount() + listSize);
            } catch (Exception e) {
                excelImport.setErrorCount(excelImport.getErrorCount() + listSize);
                log.error("Excel处理失败，类型：{}，数量：{}", excelImport.getType(), listSize, e);
            } finally {
                // 删除临时文件
                removeTempFile(file);
                if (excelImport.getCompletedCount() + excelImport.getErrorCount() == excelImport.getTotalCount()) {
                    excelImport.setStatus(GzxFileHandleStatusConstant.COMPLETED);
                }
                excelImportMapper.updateById(excelImport);
            }
        }
    }

    private void removeTempFile(File file) {
        if (file != null && file.exists()) {
            try {
                Path filePath = Paths.get(file.getAbsolutePath());
                Files.delete(filePath);
            } catch (java.nio.file.NoSuchFileException e) {
                log.error("临时文件不存在: {}", file.getAbsolutePath(), e);
            } catch (java.nio.file.DirectoryNotEmptyException e) {
                log.error("临时文件所在目录非空: {}", file.getParent(), e);
            } catch (IOException e) {
                log.error("删除临时文件时发生IO异常", e);
            } catch (SecurityException e) {
                log.error("删除临时文件时权限不足", e);
            }
        }
    }
}
